"""This module provides mydouyn"""
import time
import json
import os
import platform
import datetime
from playwright.sync_api import sync_playwright
from playwright.sync_api import Page
from auto.sleep.data import go_to_sleep
from auto.sleep.data import get_pitcute
from apscheduler.schedulers.blocking import BlockingScheduler
from apscheduler.triggers.cron import CronTrigger

########################################################################
class CToutiao:
    """
    This class represents a GetupHabit.

    Parameters:
    - save_picture_path (str): The path to save pictures.
    - default_picture_path (str): The default path for pictures.
    """
    def __init__(self,cookies_path: str, login_url: str, upload_picture_url: str, upload_mp4_url: str):
        self.cookies_path = cookies_path
        self.login_url = login_url
        self.upload_picture_url = upload_picture_url
        self.upload_mp4_url = upload_mp4_url
        # playwright 部分
        self.browser = None
        self.context = None
    def __del__(self):
        pass

    def upload_picture(self, picture_path: str, habit_name:str, habit_detail:str):
        """
          upload_picture
        """
        with sync_playwright() as playwright:
            display_headless = False
            if platform.system() == "Linux":
                display_headless = True
                self.browser = playwright.chromium.launch(headless=display_headless)
            else:
                self.browser = playwright.chromium.launch(channel="chrome",
                                                          headless=display_headless)
            login_page = self.login_or_restore_cookies()
            self.msg_up_load(login_page, picture_path, habit_name,habit_detail)
            self.browser.close()
    
    def upload_mp4(self, mp4_path: str, msg: str):
        """
          upload_mp4
        """
        with sync_playwright() as playwright:
            display_headless = False
            # display_headless = True
            sys = platform.system()
            if sys == "Linux":
                display_headless = True
            self.browser = playwright.chromium.launch(channel="chrome",headless=display_headless)
            login_page = self.login_or_restore_cookies()
            self.msg_up_load_mp4(login_page, mp4_path, msg)
            self.browser.close()
        
    
    def login_or_restore_cookies(self)-> Page:
        """
          cookies登录
        """
        user_agent ="Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/119.0.6045.21 Safari/537.36"
        sys = platform.system()
        if sys == "Linux":
            user_agent='Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/110.0.0.0 Safari/537.36'
        self.context = self.browser.new_context(user_agent=user_agent)
        self.context.clear_cookies()
        page = self.context.new_page()
        page.goto(self.login_url)
        
        if os.path.exists(self.cookies_path):
            print("cookies is exited load")
            # 从文件中加载 cookies
            with open(self.cookies_path, 'r',encoding='utf-8') as myfile:
                cookies = json.load(myfile)
            # 将 cookies 加载到页面中
            self.context.add_cookies(cookies)
            time.sleep(3)
        else:
            time.sleep(30)
            # 获取当前页面的 cookies
            cookies = page.context.cookies()
            print(cookies)
            # 保存 cookies 到文件
            with open(self.cookies_path, 'w',encoding='utf-8') as myfile:
                myfile.write(json.dumps(cookies))
        return page

    def msg_up_load(self, page: Page, picture_path: str,habit_name:str, habit_detail:str):
        """
         微头条
        """
        page.goto(self.upload_picture_url)
        page.wait_for_timeout(2000)
        print(f"open  {self.upload_picture_url}")
        page.mouse.down()
        page.evaluate("() => window.scrollTo(0,document.body.scrollHeight)")
        page.mouse.click(100,200)

        msg = habit_name + "\r\n"
        msg += habit_detail
        # 使用文本内容定位元素
        page.locator("css=.ProseMirror").fill(msg)
        print("填写标题")
        page.wait_for_timeout(2000)
        page.mouse.down()
        page.evaluate("() => window.scrollTo(0,document.body.scrollHeight)")
        
        
        page.locator("label").filter(has_text="个人观点，仅供参考").locator("div").click()
        print("个人观点，仅供参考")
        
        page.wait_for_timeout(2000)

        print("图片")
        page.locator("css=.syl-toolbar-tool.weitoutiao-image-plugin.static").click()
        page.wait_for_timeout(2000)
        # 上传图片
        with page.expect_file_chooser() as fc_info: 
            page.locator("css=.byte-btn.byte-btn-primary.byte-btn-size-huge.byte-btn-shape-square.upload-btn").locator("nth=0").click()
        file_chooser = fc_info.value
        file_chooser.set_files(picture_path)

        page.wait_for_timeout(30000)
        page.get_by_role("button", name="确定").click()

        print("结束上传图片")
        
        page.wait_for_timeout(1000)
        print("上传图片")
        page.locator("xpath=//button[./span[text()='发布']]").click()
        print("发布")
        page.wait_for_timeout(3000)

    def msg_up_load_mp4(self, page: Page, mp4_path: str, msg: str):
        """
        msg_up_load_mp4
        """
        page.goto(self.upload_mp4_url)
        time.sleep(3)
        print(f"open  {self.upload_mp4_url}")
        
        # 使用文本内容定位元素
        example_element = page.locator("xpath=//div[contains(text(), '发布视频')]")
        example_element.click()
        print("点击 发布视频")
        time.sleep(3)

        # 使用文本内容定位元素
        
        page.locator(
            "label:has-text(\"点击上传 或直接将视频文件拖入此区域为了更好的观看体验和平台安全，平台将对上传的视频预审。超过40秒的视频建议上传横版视频\")").set_input_files(
            mp4_path)
            
        print("视频文件拖入此区域")
        time.sleep(20)
        # # 点击选择文件，输入文件
        # with page.expect_file_chooser() as fc_info:
        #     # 找到拖拽区域  
        #     page.click("xpath=//button[contains(text(), '上传图片')]")
        #     # 问题 文件弹框后 不自动退出 无法后续自动化操作
        #     file_chooser = fc_info.value
        #     file_chooser.set_files(picture_path)

        # time.sleep(3)
        # page.mouse.down()
        # page.mouse.down()

        # # 填写描述
        # page.locator("css=.iGOvMbhp8tU-").fill(msg)
        # time.sleep(3)
        # # 发布
        # page.locator("xpath=//button[./span[text()='发布']]").click()
        # time.sleep(5)
        print("发布")
        time.sleep(600)
    #################################################################################


def interface_auo_upload_weitoutiao(file_path_list:str,habit_name :str,habit_detail :str):
    """
      对外调用接口
    """
    sys = platform.system()
    login_url = "https://mp.toutiao.com/profile_v4/weitoutiao/publish"
    upload_picture_url = "https://mp.toutiao.com/profile_v4/weitoutiao/publish"
    upload_mp4_url = "https://mp.toutiao.com/profile_v4/weitoutiao/publish"
    if sys == "Windows":
        cookies_path = r"D:\mp4\etc\touxiao_small.json"
        #out_path = r"D:\mp4\output"
    elif sys == "Darwin":
        cookies_path = r"/Users/wangchuanyi/mp4/etc/touxiao_small.json"
    else:
        cookies_path = r"/root/bin/touxiao_small.json"

    print("1111111")
    autoupload = CToutiao(cookies_path, login_url, upload_picture_url,upload_mp4_url)
    autoupload.upload_picture(file_path_list, habit_name,habit_detail)

def future_for_sleep():
    """
      每天写50字产品理解输出，10行代码
    """
    habit_detail = go_to_sleep.interface_go_to_sleep()
    random_images = get_pitcute.interface_get_three_pic()
    habit_name = "21点远离手机提醒"
    # 格式化为 年-月-日
    formatted_date = datetime.datetime.now().strftime('%Y-%m-%d')
    habit_name = formatted_date + " " + habit_name

    try:
        interface_auo_upload_weitoutiao(random_images, habit_name, habit_detail)
    except Exception as err:
        print(f"Unexpected {err=}, {type(err)=}")

if __name__ == '__main__':
    # playwright codegen  https://mp.toutiao.com/profile_v4/weitoutiao/publish
    future_for_sleep()
    job_defaults = {
        'coalesce': False,
        'max_instances': 1
    }
    # 调度器组件
    backsched = BlockingScheduler(job_defaults=job_defaults, timezone='Asia/Shanghai')
    # future_for_sleep callable函数 习惯养成--早睡早起
    # crontab 是 Linux 系统中用于设置周期性被执行的指令的命令
    # 0 0 * * *	每天的午夜（0 点）执行一次
    backsched.add_job(future_for_sleep, CronTrigger.from_crontab("10 21 * * *"), id="get_up")
    backsched.start()